ibm-watson-machine-learning¶This notebook contains the steps and code to demonstrate support of AutoAI experiments for timeseries data sets in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, deploying pipelines, and scoring.
Some familiarity with Python is helpful. This notebook uses Python 3.9.
The learning goals of this notebook are:
This notebook contains the following parts:
Before you use the sample code in this notebook, you must perform the following setup tasks:
Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide Cloud API key and location.
Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) Service instance details.
You can use IBM Cloud CLI to retrieve the instance location.
ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME
NOTE: You can also get a service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, and then copy the created key and paste it in the following cell.
Action: Enter your api_key and location in the following cell.
api_key = ''
location = ''
wml_credentials = {
"apikey": api_key,
"url": 'https://' + location + '.ml.cloud.ibm.com'
}
!pip install -U ibm-watson-machine-learning | tail -n 1
!pip install wget | tail -n 1
!pip install plotly | tail -n 1
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/envs/Python-3.9/lib/python3.9/site-packages (from packaging->ibm-watson-machine-learning) (3.0.4) Requirement already satisfied: wget in /opt/conda/envs/Python-3.9/lib/python3.9/site-packages (3.2) Requirement already satisfied: six in /opt/conda/envs/Python-3.9/lib/python3.9/site-packages (from plotly) (1.15.0)
from ibm_watson_machine_learning import APIClient
client = APIClient(wml_credentials)
You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.
space_id and paste it belowTip: You can also use SDK to prepare the space for your work. More information can be found here.
Action: assign space ID below
space_id = ''
You can use the list method to print all existing spaces.
client.spaces.list(limit=10)
To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.
client.set.default_space(space_id)
'SUCCESS'
In next cell we read the COS credentials from the space.
cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']
Download training data from git repository and upload it to a COS.
This example uses the China daily PM2.5.
datasource_name = 'bluemixcloudobjectstorage'
bucketname = cos_credentials['bucket_name']
import os, wget, zipfile
filename = 'PM25.csv'
base_url = 'https://raw.githubusercontent.com/wjcougar/air_pollution/master/'
if not os.path.isfile(filename): wget.download(base_url + filename)
import plotly.express as px
import pandas as pd
df = pd.read_csv(filename)
fig = px.line(df, x='date', y=df.columns)
fig.show()
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': bucketname,
'access_key': cos_credentials['credentials']['editor']['access_key_id'],
'secret_key': cos_credentials['credentials']['editor']['secret_access_key'],
'iam_url': 'https://iam.cloud.ibm.com/identity/token',
'url': cos_credentials['endpoint_url']
}
}
conn_details = client.connections.create(meta_props=conn_meta_props)
Creating connections... SUCCESS
Note: The above connection can be initialized alternatively with api_key and resource_instance_id.
The above cell can be replaced with:
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': bucket_name,
'api_key': cos_credentials['apikey'],
'resource_instance_id': cos_credentials['resource_instance_id'],
'iam_url': 'https://iam.cloud.ibm.com/identity/token',
'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'
}
}
conn_details = client.connections.create(meta_props=conn_meta_props)
connection_id = client.connections.get_uid(conn_details)
The code in next cell defines connections to created assets.
from ibm_watson_machine_learning.helpers import DataConnection, S3Location
data_connections = []
data_connection = DataConnection(
connection_asset_id=connection_id,
location=S3Location(bucket=cos_credentials['bucket_name'],
path=filename)
)
data_connection.set_client(client)
data_connection.write(data=filename, remote_name=filename)
data_connections.append(data_connection)
Provide the input information for AutoAI optimizer:
name - experiment nameprediction_type - type of the problemprediction_columns - target columns namestimestamp_column_name — date&time column name/indexfeature_columns – names/indices of supporting feature columnsforecast_window — future date/time range to be predictedholdout_size - number of holdout recordslookback_window – past date/time range used for model training, -1 means auto-determinedbacktest_num – number of backtestssupporting_features_at_forecast – whether leveraging future values of supporting featurespipeline_types – specify an indiviual or a group of pipelins by typefrom ibm_watson_machine_learning.experiment import AutoAI
from ibm_watson_machine_learning.utils.autoai.enums import ForecastingPipelineTypes
experiment = AutoAI(wml_credentials, space_id=space_id)
forecast_window = 7
backtest_num = 4
pipeline_optimizer = experiment.optimizer(
name="PM25 prediction",
prediction_type=AutoAI.PredictionType.FORECASTING,
prediction_columns=['pollution'],
timestamp_column_name='date',
feature_columns=['pollution','dew','temp','press','wnd_spd','snow','rain'],
lookback_window=-1,
backtest_num=backtest_num,
holdout_size=14,
forecast_window=forecast_window,
supporting_features_at_forecast=True,
pipeline_types=[ForecastingPipelineTypes.Bats] + ForecastingPipelineTypes.get_exogenous()
)
Configuration parameters can be retrieved via pipeline_optimizer.get_params().
Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.
fit_details = pipeline_optimizer.fit(training_data_reference=data_connections, background_mode=False)
Training job 18f150bb-4581-4d70-be33-49d3a466b0d0 completed: 100%|████████| [05:20<00:00, 3.20s/it]
You can use the get_run_status() method to monitor AutoAI jobs in background mode.
pipeline_optimizer.get_run_status()
'completed'
You can list trained pipelines and evaluation metrics information in
the form of a Pandas DataFrame by calling the summary() method. You can
use the DataFrame to compare all discovered pipelines and select the one
you like for further deployment.
summary = pipeline_optimizer.summary()
summary
| Enhancements | Estimator | Winner | Type | validation_symmetric_mean_absolute_percentage_error | holdout_avg_r2 | holdout_avg_mean_absolute_error | holdout_avg_root_mean_squared_error | holdout_avg_symmetric_mean_absolute_percentage_error | holdout_mean_absolute_error | ... | holdout_symmetric_mean_absolute_percentage_error | holdout_r2 | backtest_avg_r2 | backtest_avg_mean_absolute_error | backtest_avg_root_mean_squared_error | backtest_avg_symmetric_mean_absolute_percentage_error | backtest_mean_absolute_error | backtest_root_mean_squared_error | backtest_symmetric_mean_absolute_percentage_error | backtest_r2 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Pipeline Name | |||||||||||||||||||||
| Pipeline_4 | HPO, FE | Ensembler | True | exogenous | 42.446582 | 0.570773 | 37.987089 | 61.398038 | 35.241435 | 37.987089 | ... | 35.241435 | 0.570773 | 0.649023 | 32.824713 | 48.311141 | 30.368102 | 32.824713 | 48.311141 | 30.368102 | 0.649023 |
| Pipeline_1 | HPO, FE | RandomForest | True | exogenous | 46.987713 | 0.267621 | 58.455268 | 80.200856 | 58.607427 | 58.455268 | ... | 58.607427 | 0.267621 | 0.283918 | 46.957749 | 56.460090 | 51.193633 | 46.957749 | 56.460090 | 51.193633 | 0.283918 |
2 rows × 21 columns
Check pipeline details by calling get_pipeline_details(). By default details of best pipeline are returned.
best_pipeline_name = summary[summary.Winner==True].index.values[0]
print('Best pipeline is:', best_pipeline_name)
pipeline_details = pipeline_optimizer.get_pipeline_details()
Best pipeline is: Pipeline_4
from datetime import datetime, timedelta
import numpy as np
visualization = pipeline_details['visualization']['holdout']
holdout_dates = visualization['time']
holdout_predictions = visualization['predicted_values'][0]
holdout_observed_values = visualization['observed_values'][0]
holdout_df = pd.DataFrame({'time':holdout_dates, 'observed_values':holdout_observed_values, 'predicted_values': holdout_predictions})
fig = px.line(holdout_df, x="time", y=holdout_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Holdout data')
fig.update_xaxes(dtick="M1", tickformat="%b\n%Y")
fig.show()
from datetime import datetime, timedelta
import numpy as np
backtest_dfs = []
for i in range(backtest_num):
visualization = pipeline_details['visualization']['backtest']['iterations'][i]
backtest_dates = visualization['time']
backtest_predictions = visualization['predicted_values'][0]
observed_values = visualization['observed_values'][0]
backtest_dfs.append(pd.DataFrame({'time':backtest_dates, 'observed_values':observed_values, 'predicted_values': backtest_predictions}))
backtest_df = pd.concat(backtest_dfs)
fig = px.line(backtest_df, x="time", y=backtest_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Backtest data')
fig.update_xaxes(dtick="M1", tickformat="%b\n%Y")
fig.show()
In this section you will learn how to deploy and score pipeline model as online deployment using WML instance.
from ibm_watson_machine_learning.deployment import WebService
service = WebService(wml_credentials, source_space_id=space_id)
service.create(
experiment_run_id=pipeline_optimizer.get_run_details()['metadata']['id'],
model=best_pipeline_name,
deployment_name="PM2.5 Forecasting"
)
To show all available information about the deployment use the .get_params() method:
service.get_params()
You can use the score method to get predictions for defined forecasting window. You can either send payload records or use empty list.
predictions = service.score(payload=pd.DataFrame({'daily_cases' : []}))
print('predictions for next 7 days:\n')
predictions
predictions for next 7 days:
{'predictions': [{'fields': ['prediction'],
'values': [[[129.5439294077758]],
[[129.81703947189507]],
[[126.70353558876782]],
[[123.59116561586549]],
[[126.16670897809692]],
[[130.53538843411673]],
[[134.82070412310827]]]}]}
Or you could send payload with new obeservations:
filename = 'PM25_NewObservations.csv'
if not os.path.isfile(filename): wget.download(base_url + filename)
predictions = service.score(pd.read_csv(filename).drop("date", axis=1))
predictions
last_date = datetime.strptime(holdout_df.tail(1).time.values.tolist()[0],'%Y-%m-%d')
prediction_dates = [(last_date + timedelta(days=1 + i)).date() for i in range(forecast_window)]
prediction_values = [pred[0][0] for pred in predictions['predictions'][0]['values']]
pred_df = pd.DataFrame({'time' : holdout_dates + prediction_dates,
'observed_values' : holdout_observed_values + [np.NAN for i in range(forecast_window)],
'predicted_values' : holdout_predictions + prediction_values})
fig = px.line(pred_df, x="time", y=pred_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Forecast data')
fig.update_xaxes(dtick="M1", tickformat="%b\n%Y")
fig.show()
If you want to clean up all created assets:
please follow up this sample notebook.
You successfully completed this notebook!.
You learned how to use ibm-watson-machine-learning to run AutoAI experiments.
Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.
Jun Wang, is a Software Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.
Copyright © 2020, 2021, 2022 IBM. This notebook and its source code are released under the terms of the MIT License.